<template>
    <el-dialog
        :before-close="handleClose"
        class="select-account-dialog"
        align-center
        :title="title"
        v-model="visible"
        width="800px">
        <div class="select-account-dialog-body">
            <div class="select-account-dialog-table">
                <el-form ref="formRef" :model="Data.formData">
                    <el-checkbox-group v-model="checkList">
                        <el-table :data="tableList" :height="400" type="expand" :default-expand-all="true" row-key="id">
                            <el-table-column
                                v-for="{ prop, ...rest } in tableColumns"
                                :key="prop"
                                :prop="prop"
                                v-bind="rest">
                                <template #default="{ row }">
                                    <template v-if="prop === 'corp_name'">
                                        <div class="corp-name">
                                            <div class="corp-name-main">
                                                <ZwTooltip :content="row.corp_name" :line="2" />
                                            </div>
                                            <div class="corp-name-sub" v-if="row.corp_unified_social_credit_code">
                                                <ZwTooltip :content="row.corp_unified_social_credit_code" />
                                            </div>
                                        </div>
                                    </template>
                                    <template v-if="prop == 'ratio'">
                                        <template v-if="['add', 'edit'].includes(type)">
                                            <el-form-item
                                                :prop="`ratio${row.id}`"
                                                :rules="[{ validator: checkRatioNum, trigger: 'blur' }]">
                                                <div style="margin-top: 18px">
                                                    <el-input-number
                                                        :precision="2"
                                                        :controls="false"
                                                        placeholder="请输入"
                                                        style="width: 60%; margin-right: 5px"
                                                        v-model="Data.formData['ratio' + row.id]" />
                                                    %
                                                </div>
                                            </el-form-item>
                                        </template>
                                        <template v-else>
                                            <span>{{ getRadio(row.ratio) }}</span>
                                        </template>
                                    </template>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-checkbox-group>
                </el-form>
            </div>
        </div>
        <template #footer>
            <div v-if="type === 'add'" class="custom-footer">
                <el-button @click="prevHandle">上一步</el-button>
                <el-button type="primary" @click="comfirmHandler">确定</el-button>
            </div>
            <div v-else-if="type === 'edit'" class="custom-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-popconfirm
                    width="200"
                    title="修改后将立即生效，确定要修改吗？"
                    :hide-after="0"
                    trigger="contextmenu"
                    :visible="popconfirmVisible"
                    @confirm="comfirmSubmit"
                    @cancel="popconfirmVisible = false">
                    <template #reference>
                        <el-button type="primary" @click="comfirmHandler">确定</el-button>
                    </template>
                </el-popconfirm>
            </div>
            <div v-else class="custom-footer">
                <el-button type="primary" @click="visible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/request/index';
import ZwTooltip from '@/components/ZwTooltip.vue';

/* ---------------------------------- 父级通信 start ---------------------------------- */
const emit = defineEmits(['handle-confirm', 'update:modelValue', 'handle-prev']);
const props = defineProps({
    // 是否显示控制按钮
    modelValue: {
        type: Boolean,
        default: false
    },
    tableData: {
        type: Array,
        default: () => []
    },
    splitOpenId: {
        type: String,
        default: ''
    },
    // add、新增， edit、编辑  look、查看
    type: {
        type: String,
        default: 'look'
    },
    splitType: {
        type: String,
        default: ''
    }
});
/* ---------------------------------- 父级通信 end ---------------------------------- */

/* ---------------------------------- 控制弹窗 start ---------------------------------- */
const visible = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

const title = computed(() => {
    const types = {
        add: '设置分账比例',
        edit: '修改分账比例',
        look: '查看分账信息'
    };
    return types[props.type];
});

const tableList = computed(() => {
    const arr = [];
    props.tableData.map(x => {
        arr.push(x);
    });
    return arr;
});

watch(
    () => props.modelValue,
    val => {
        if (val) {
            getFormData();
        }
    }
);

watch(
    () => visible.value,
    val => {
        if (!val) {
            popconfirmVisible.value = false;
        }
    }
);

const formRef = ref();
const Data = reactive({
    formData: {}
});

const getFormData = () => {
    const obj = {};
    props.tableData.forEach(x => {
        obj['ratio' + x.id] = Number(x.ratio) || NaN;
    });
    Data.formData = obj;
};

// 分账比例数字框校验
const checkRatioNum = (rules, value, callback) => {
    const prop = rules.field;
    if ([null, '', NaN].includes(Data.formData[prop])) {
        callback(new Error('请输入分账比例'));
    }
    if (Data.formData[prop] <= 0) {
        return callback(new Error('分账比例需要大于0'));
    }
    if (Data.formData[prop] > 99) {
        return callback(new Error('分账比例不能大于99'));
    }
    callback();
};

const checkList = ref([]);

// 格式化比例
const getRadio = val => (props.splitType === 'API' || ['--', null, undefined, ''].includes(val) ? '--' : val + '%');

/**
 * 列表配置项
 */
const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '分账接收方信息', prop: 'corp_name', minWidth: '280' },
        { label: '主体类型', prop: 'corp_main_type_name', minWidth: '170' },
        { label: '分账比例', prop: 'ratio', minWidth: '140' }
    ];
    return baseTableColumns;
});

const popconfirmVisible = ref(false);
// 添加(编辑)分账接收方
const comfirmHandler = () => {
    popconfirmVisible.value = false;
    formRef.value.validate(valid => {
        if (valid) {
            if (props.type === 'edit') {
                popconfirmVisible.value = true;
            } else {
                comfirmSubmit();
            }
        }
    });
};

//  添加(编辑)分账接收方提交接口
const comfirmSubmit = async () => {
    const para = {
        split_account_id: props.splitOpenId,
        split_account_receiver: []
    };
    tableList.value.forEach(x => {
        para.split_account_receiver.push({
            open_no: x.split_open_no || x.open_no,
            split_account_receiver_id: props.type == 'add' ? '' : x.id,
            ratio: String(Data.formData['ratio' + x.id]) || ''
        });
    });
    if (props.type == 'add') {
        await request('addReceiverSplitAccountServ', para);
        emit('handle-confirm', true);
    } else {
        await request('editReceiverSplitAccountServ', para);
        emit('handle-confirm', true);
        visible.value = false;
    }
};

// 上一步
const prevHandle = () => {
    const arr = [];
    props.tableData.forEach(x => {
        arr.push(Object.assign(x, { ratio: Data.formData[`ratio${x.id}`] }));
    });
    emit('handle-prev', arr);
};

// 手动关闭弹窗时
const handleClose = done => {
    emit('handle-confirm', false);
    done();
};
</script>
<style lang="scss" scoped>

:deep(.el-input-number .el-input__inner) {
    text-align: left;
}
.select-account-dialog-search {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-input {
        width: 300px;
    }
}

.select-account-dialog-table {
    margin-top: 18px;
}

.corp-name-main {
    font-size: 14px;
    font-weight: 400;
    color: #33302d;
    margin-bottom: 8px;
    padding: 0 5px;
}

.corp-name-sub {
    font-size: 14px;
    font-weight: 400;
    color: #999999;
    line-height: 14px;
    padding: 0 5px;
}

.custom-status-point {
    display: flex;
    align-items: center;
    line-height: normal;

    &::before {
        content: '';
        display: inline-block;
        width: 8px;
        height: 8px;
        margin-right: 8px;
        background-color: var(--status-bgcolor);
        border-radius: 4px;
    }

    .custom-status-icon {
        cursor: pointer;
        width: 16px;
        height: 16px;
        margin-left: 6px;
    }
}
</style>
